import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ReportFormEmbedComponent } from 'src/app/embed/report-form-embed/report-form-embed.component';
import { MemberVo } from 'src/app/model/member-vo';
import { ThreadsCollectStatsAndBoard } from 'src/app/model/threads-collect-stats-and-board';
import { BtnNaviSharedService } from 'src/app/services/btn-navi-shared.service';
import { MemberStorageService } from 'src/app/services/member-storage.service';
import { ThreadsService } from 'src/app/services/threads.service';
import { UtilService } from 'src/app/services/util.service';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styles: [``]
})
/**
 * 主页
 * @constructor
 */
export class MainComponent implements OnInit {
  public items: ThreadsCollectStatsAndBoard[] = [];
  public errorMessage: string = '';
  public curMember: MemberVo | null;
  //引用举报的子组件
  @ViewChild('reportF', { static: false })
  public reportFormCmp!: ReportFormEmbedComponent;
  private ip:string = '127.0.0.1';

  constructor(
    private title: Title,
    private threadsService: ThreadsService,
    private memberStorage: MemberStorageService,
    private util: UtilService,
    private btnNaviSharedService: BtnNaviSharedService) {
    this.btnNaviSharedService.active(true);//需要全局的导航
    this.curMember = this.memberStorage.get();
    this.memberStorage.getIpCliente().subscribe(ipAddr=>this.ip=ipAddr);
  }

  ngOnInit(): void {
    this.title.setTitle("随便看看")
    this.threadsService.getRecent(environment.recentSize).subscribe(res=>this.items = res);
  }
  //打开举报抽屉菜单
  public toggleReport(topicId: number): void {
    return this.reportFormCmp.toggleThreadsDrawer(topicId);
  }

  //举报话题
  public reportThreads(reportData: any): void {
    if (this.curMember === null) {
      this.util.alertError('暂不支持游客举报话题');
      return;
    }
    this.threadsService.report(reportData.threads, reportData.reason, reportData.type, this.curMember?.id ?? 0, this.curMember?.nickname ?? 'guest', reportData.token, this.ip).subscribe({
      next: response => {
        this.util.alertSuccess("话题举报成功");
      },
      error: err => {
        let em: string = '';
        if (err instanceof HttpErrorResponse) {
          if (err.error instanceof ErrorEvent) {
            em = err.error.message;
          } else {
            em = err.error;
          }
        } else if (err instanceof Error) {
          em = err.message;
        } else { em = err; }
        this.util.alertError(em);
        console.log('[Home-CTL]report topic error ' + em);
      },
      complete: () => {
        console.log('[Home-CTL]report topic Completed');
        this.reportFormCmp.close();
      }
    });
  }

}
